import axios from 'axios'
import { Loading, MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, getSignKey, getAppApiUrl, setDjhSafeKey, getDjhSafeKey } from '@/utils/auth'

const loading = { //loading加载对象
  loadingInstance: null,
  //打开加载
  open(msg) {
    if (this.loadingInstance === null) { // 如果实例 为空，则创建
      this.loadingInstance = Loading.service({
        text: msg ? msg : '加载中...', //加载图标下的文字
        spinner: 'el-icon-loading', //加载图标
        background: 'rgba(0, 0, 0, 0.8)', //背景色
        customClass: 'loading' //自定义样式的类名
      })
    }
  },
  //关闭加载
  close() {
    // 不为空时, 则关闭加载窗口
    if (this.loadingInstance !== null) {
      this.loadingInstance.close()
    }
    this.loadingInstance = null
  }
}
axios.defaults.headers['Accept'] = 'application/json'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: getAppApiUrl(),
  // 超时
  timeout: 20000
})
// request拦截器
service.interceptors.request.use(config => {
  if (config.loadingFlag) {
    //打开加载窗口
    loading.open(config.loadingMsg)
  }
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  //将token设置成请求头
  if (getToken() && !isToken) {
    config.headers["token"] = getToken()
  }
  //将安全key设置成请求头
  if (getDjhSafeKey()) {
    config.headers["djhSafeKey"] = getDjhSafeKey()
  }
  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?'
    for (const propName of Object.keys(config.params)) {
      const value = config.params[propName]
      var part = encodeURIComponent(propName) + '='
      if (value !== null && typeof (value) !== 'undefined') {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            if (value[key] !== null && typeof (value[key]) !== 'undefined') {
              let params = propName + '[' + key + ']'
              let subPart = encodeURIComponent(params) + '='
              url += subPart + encodeURIComponent(value[key]) + '&'
            }
          }
        } else {
          url += part + encodeURIComponent(value) + '&'
        }
      }
    }
    url = url.slice(0, -1)
    config.params = {}
    config.url = url
  }
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    //关闭加载窗口
    loading.close()
    if (res.data.errorCode < 0) {
      MessageBox.alert(
        res.data.message,
        '系统提示',
        {
          confirmButtonText: '重新登录',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      })
    } else if (res.data.errorCode === 0) {
      //设置请求头返回的安全key
      setDjhSafeKey(res.headers['djhsafekey'])
      //返回内容值
      return res.data
    } else {
      Message({
        errorCode: res.data.errorCode,
        message: res.data.message,
        type: 'error'
      })
      return Promise.reject(res.data.message)
    }
  },
  error => {
    //关闭加载窗口
    loading.close()
    console.log('err' + error)
    let { message } = error
    if (message === 'Network Error') {
      message = '服务接口连接异常'
    } else if (message.includes('timeout')) {
      message = '服务接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '服务接口' + message.substr(message.length - 3) + '异常'
    }
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
